<template>
  <div>
    <div class="demo-upload-list" v-for="item in imageList">
      <template v-if="item.status === 'finished'">
        <img :src="item.url">
        <div class="demo-upload-list-cover">
          <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
          <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
        </div>
      </template>
    </div>
    <div class="db_inline" style="vertical-align: top;" v-if="multiple||imageList.length===0">
      <Upload
        :show-upload-list="false"
        :default-file-list="defaultList"
        :on-success="handleSuccess"
        :accept="accept"
        :max-size="maxSize"
        :on-exceeded-size="handleMaxSize"
        :before-upload="handleBeforeUpload"
        :on-error="handleError"
        :multiple="multiple"
        type="drag"
        :data="data"
        :headers="headers"
        :action="action"
        style="display: inline-block;width:80px;">
        <div class="db_inline" style="width: 80px;height:80px;line-height: 80px;">
          <Icon type="camera" size="20"></Icon>
        </div>
      </Upload>
      <slot name="notice"></slot>
      <!--<div class="db_inline notice">（注：文件大小不要超过{{maxSize/1024}}M！）</div>-->
    </div>
    <Modal title="查看大图" v-model="visible" class="check_pig">
      <img :src="pre.url" v-if="visible" style="width: 100%;">
    </Modal>
  </div>
</template>
<script>
  import API from "@/api/api";
  import Cookie from "js-cookie"
  import Axios from 'axios'

  export default {
    props: {
      accept: {
        type: String,
        default: 'null'
      },
      maxSize: {
        type: Number,
        default: 2048
      },
      multiple: {
        type: Boolean,
        default: true,
      },
      delImgPath: {
        type: String,
        default: ''
      },
    },
    data() {
      return {
        defaultList: [],
        pre: {
          url: ''
        },
        visible: false,
        domain: Cookie.getJSON('cdnUrl'),
        imageList: [],
        action: Axios.defaults.baseURL + '/cos/upload',
        headers: {
          Authorization: "Bearer " + Cookie.getJSON('TOKEN')
        },
        data: {
          token: Cookie.getJSON('uploadToken'),
        },
        vframe: '?vframe/jpg/offset/2',
      }
    },
    methods: {
      //父组件传递 {id:'',key:'',fname:'',type:''}对象数组到子组件
      acceptImageList(arrayData) {
        this.imageList = [];
        for (let i in arrayData) {
          let key = arrayData[i].key;//存储的文件名
          let fname = arrayData[i].fname;//源文件名
          let url = this.domain + key;
          url += arrayData[i].type === 'video' ? this.vframe : "";
          let obj = {
            id: arrayData[i].id,
            name: key,
            status: 'finished',
            fname: fname,
            url: url
          };
          this.imageList.push(obj);
        }
      },
      handleView(file) {
        this.visible = true;
        this.pre.url = file.url;
      },
      //传递数据给父组件
      popImageList(oldList, newFile) {
        this.$emit('get-file', oldList, newFile);
      },
      removeUploadFile(file) {
        let obj = {
          name: file.name,
          fname: file.fname,
          url: file.url,
          status: file.status
        };
        this.$emit('remove-file', obj);
      },
      handleRemove(file) {
        if (file.id && this.delImgPath) {
          API.del(this.delImgPath, {fileName: file.id}).then(resp => {
            this.imageList.splice(this.imageList.indexOf(file), 1);
            this.removeUploadFile(file);
          });
        } else if (!file.id) {
          API.deleteFromTencent({
            fileName: file.name
          }).then(resp => {
            this.imageList.splice(this.imageList.indexOf(file), 1);
            this.removeUploadFile(file);
          });
        }
      },
      handleError(error, file, fileList) {
        this.$Message.error('上传失败！');
        this.$Spin.hide();
      },
      handleSuccess(resp, file) {
        let res = resp.data;
        this.$Spin.hide();
        file.url = this.domain + res.key;
        if (".mp4" === res.ext) {
          file.url += '?vframe/jpg/offset/3';
        }
        file.name = res.key;
        file.fname = res.fname;
        let temp = [];
        for (let i in this.imageList) {
          temp.push(this.imageList[i]);
        }
        let newFile = {
          fname: file.fname,
          name: file.name,
          status: file.status,
          url: file.url
        };
        this.imageList.push(newFile);
        this.popImageList(temp, newFile);
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: '图片大小超出！',
          desc: '请选择小于' + this.maxSize / 1024 + '的文件!'
        });
      },
      handleBeforeUpload(file) {
        this.$Spin.show({
          render: (h) => {
            return h('div', [
              h('Icon', {
                'class': 'demo-spin-icon-load',
                props: {
                  type: 'load-c',
                  size: 18
                }
              }),
              h('div', '上传中...')
            ])
          }
        });
      }
    },
    mounted() {
    },
    created() {
    }
  }
</script>
<style type="text/css" scoped>
  .demo-upload-list {
    display: inline-block;
    width: 80px;
    height: 80px;
    text-align: center;
    line-height: 80px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .check_pig {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 9999;
  }
</style>
